import 'dart:async';
import 'dart:ui';

import 'package:card_swiper/card_swiper.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/channel_apis.dart';
import 'package:flutter_syt/datas/article_item.dart';
import 'package:flutter_syt/datas/category_info_model.dart';
import 'package:flutter_syt/datas/category_v3_model.dart';
import 'package:flutter_syt/datas/home_announcement_mdoel.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/home/share_api.dart';
import 'package:flutter_syt/domain/news/news_focus_page.dart';
import 'package:flutter_syt/domain/widgets/flow_item.dart';
import 'package:flutter_syt/domain/widgets/home_title_bar.dart';
import 'package:flutter_syt/domain/widgets/network_load_image.dart';
import 'package:flutter_syt/domain/widgets/scroller_banner.dart';
import 'package:flutter_syt/domain/widgets/simple_image_loader.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/auto_image.dart';
import 'package:flutter_syt/widgets/home_count_down.dart';
import 'package:flutter_syt/widgets/normal_table.dart';
import 'package:flutter_syt/widgets/web_detail.dart';
import 'package:flutter_syt/widgets/web_video_page.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import 'home_cover.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // double _offset = 0;

  // List<GridNavItemEntity> categoryList2 = [];
  // List<GridNavItemEntity> categoryServices = [];
  // List<FlowItemEntity> topArticles = [];
  // List<Encyclopedias> baikeList = [];
  HomeCoverEntity? _currentCover;
  final SwiperController _swipeController = SwiperController();
  final NormalTableViewController _normalTableViewController =
      NormalTableViewController();
  CategoryV3Model _categoryV3Model =
      CategoryV3Model(position1: [], position2: [], position3: []);
  // Timer? timer;
  List<HomeAnnouncementMdoel> _announcementRows = [];
  int _countDownTime = 0;
  double _spacWidth = 0;
  List<FlowItemEntity> topArticles = [];

  @override
  void initState() {
    UserInfo.me.addListener(() {
      _normalTableViewController.reloadData();
    });
    // timer?.cancel();
    // timer = Timer.periodic(Duration(minutes: 1), (timer) {
    //   setState(() {});
    //   DLog('daslkdjalksjd');
    // });
    checkPushPermission();
    super.initState();
  }

  checkPushPermission() async {
    var status = await Permission.notification.status;
    if (status.isDenied || status.isGranted) {
      PermissionStatus status = await Permission.notification.request();
      // Permission.accessNotificationPolicy.request();
      print('PermissionStatus  $status');
    }
    var status1 = await Permission.notification.status;
    if (status1.isGranted) {
      appContext.channelApi.initSDK();
    }

    // if (UserInfo.me.isLogin) {
    // PermissionUtil.checkPermissionStatus(Permission.notification);
    // }
    // Future.delayed(Duration(seconds: 1), () {
    //
    // });
  }

  @override
  dispose() {
    // timer?.cancel();
    super.dispose();
  }

  loadData() async {
    await fetchHomeBanner();
    await queryWeather();

    // 栏目
    try {
      // List<CategoryItem> categoryAll = await API.shared.common.allCategory();
      _categoryV3Model = await API.shared.common.getCategoryHome();

      _announcementRows = await API.shared.common.getHomeAnnouncement();
      // _categoryV3Model.position2?.add(_categoryV3Model.position2!.first);
      // _categoryV3Model.position2?.add(_categoryV3Model.position2!.first);
      // if (data is List) {
      //   _announcementRows = data
      //       .map((e) =>
      //           HomeAnnouncementMdoel.fromJson(e as Map<String, dynamic>))
      //       .toList();
      // }

      var json = await API.shared.common.getSystemSetting('countdown');
      if (json is Map) {
        if (json['value'] != null && json['value'] is int) {
          _countDownTime = (json['value']) * 1000;
        }
      }

      if (mounted) {
        setState(() {});
      }
    } catch (e, stack) {
      // DLog('msg   ${stack.toString()}  ${e}');
      debugPrintStack(stackTrace: stack);

      UtilsOther.showCustomShowError(e);
    }
  }

  bool isRefreshing = false;

  Widget countDownView() {
    return HomeCountDown(countDownTime: _countDownTime);
  }

  void _jingangJump(CategoryInfoModel e) {
    if (e.monitorStatus == 0) {
      customShowToast(S.current.comment_serviceupdate);
      return;
    }
    var uri = Uri.parse(e.path ?? '');
    var fullPaths = uri.pathSegments;
    API.shared.common.getColumnStatistics(e.name ?? '');
    var path = '';
    try {
      path = fullPaths.first;
    } catch (e) {}
    if (path == 'web_detail') {
      var parameters = uri.queryParameters;
      Map<String, String> args = {};
      parameters.forEach((key, value) {
        args[key] = value;
      });
      var url = "${args['url']}";
      if (url.isEmpty || url == 'null') {
        // launchUrlString('urlString', mode: LaunchMode.externalApplication);
        RouteManager.push(context, e.path ?? '');
      } else {
        if (e.isWebView == 1) {
          var web = WebVideoPage(
            url,
            needBar: e.headOccupy == 1,
          );
          web.openCheckPhotos = e.isOpenBig == 1;
          // var web = WebVideoPage(url);
          // 占用是不显示原生的，所以为1的时候不显示
          // web.needBar = e.headOccupy == 1;
          Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => web,
              settings: RouteSettings(name: "web_detail", arguments: "")));
        } else {
          var web = WebDetailPage(url);
          // var web = WebVideoPage(url);
          // 占用是不显示原生的，所以为1的时候不显示
          web.needBar = e.headOccupy == 1;
          web.openCheckPhotos = e.isOpenBig == 1;
          Navigator.of(context).push(MaterialPageRoute(
              builder: (context) => web,
              settings: RouteSettings(name: "web_detail", arguments: "")));
        }
      }
    } else {
      RouteManager.push(context, e.path ?? '');
    }
  }

  Widget jingangWidgetItem(CategoryInfoModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ClickUtils.debounce(() {
        _jingangJump(model);
      }),
      child: Container(
        // margin: EdgeInsets.only(bottom: 16),
        width: (1.sw - 30.w) / 4,
        // height: 80.w,
        // color: Colors.red,
        child: Column(
          // mainAxisSize: MainAxisSize.min,
          // mainAxisAlignment: MainAxisAlignment.start,
          children: [
            ImageLoader.loadImage(
              imageUrl: model.icon ?? '',
              width: 48.w,
              height: 48.w,
            ),
            SizedBox(
              height: 2,
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Flexible(
                    // padding: EdgeInsets.symmetric(horizontal: 5),
                    child: Text(
                      // 'asdkfasdlkfjsdlkj',
                      model.name ?? '',
                      maxLines: 2,
                      textAlign: TextAlign.center,
                      style: FontStyles.headerTextStyle_12.copyWith(
                        color: ThemeColor.colorBlack80,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  List<List<CategoryInfoModel>> jingangWrapData() {
    // _categoryV3Model.position1?.first.name = 'data source casc';
    if ((_categoryV3Model.position1 ?? []).isNotEmpty) {
      if ((_categoryV3Model.position1 ?? []).length > 4) {
        return [
          (_categoryV3Model.position1 ?? []).sublist(0, 4),
          (_categoryV3Model.position1 ?? [])
              .sublist(4, (_categoryV3Model.position1 ?? []).length)
        ];
      } else {
        return [
          (_categoryV3Model.position1 ?? [])
              .sublist(0, (_categoryV3Model.position1 ?? []).length),
          []
        ];
      }
    } else {
      return [[], []];
    }
// return [];
  }

  Widget jingangWidget() {
    List<List<CategoryInfoModel>> lists = jingangWrapData();
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: Column(
        children: [
          Visibility(
              visible: lists.first.isNotEmpty,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: lists.first.map((e) {
                  return jingangWidgetItem(e);
                }).toList(),
              )),
          Visibility(
              visible: lists.last.isNotEmpty,
              child: SizedBox(
                height: 16,
              )),
          Visibility(
              visible: lists.last.isNotEmpty,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: lists.last.map((e) {
                  return jingangWidgetItem(e);
                }).toList(),
              )),
        ],
      ),
    );
  }

  Widget baikeWidget() {
    if ((_categoryV3Model.position2 ?? []).isEmpty) {
      return Container();
    }
    PositionWrap positionWrap = PositionWrap(_categoryV3Model.position2 ?? []);
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      // width: 1.sw,
      child: Column(
        crossAxisAlignment: positionWrap.bottomList.length < 3
            ? CrossAxisAlignment.start
            : CrossAxisAlignment.center,
        children: [
          Padding(
              padding: EdgeInsets.only(
                top: 24,
                bottom: 12,
              ),
              child: Row(
                children: [
                  Text(
                    _categoryV3Model.baikeName ?? '',
                    textAlign: TextAlign.left,
                    style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontFamily: "PingFang SC",
                    ),
                  )
                ],
              )),
          _buildPostionTopView(_categoryV3Model.position2 ?? []),
          _buildPostionBottomView(_categoryV3Model.position2 ?? []),
        ],
      ),
    );
  }

  Widget serviceWidget() {
    if ((_categoryV3Model.position3 ?? []).isEmpty) {
      return Container();
    }
    PositionWrap positionWrap = PositionWrap(_categoryV3Model.position3 ?? []);
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      // width: 1.sw,
      child: Column(
        // crossAxisAlignment: CrossAxisAlignment.start,
        crossAxisAlignment: positionWrap.bottomList.length < 3
            ? CrossAxisAlignment.start
            : CrossAxisAlignment.center,
        children: [
          Padding(
              padding: EdgeInsets.only(
                top: 24,
                bottom: 12,
              ),
              child: Row(
                children: [
                  Text(
                    _categoryV3Model.serviceName ?? '',
                    textAlign: TextAlign.left,
                    style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontFamily: "PingFang SC",
                    ),
                  )
                ],
              )),
          _buildPostionTopView(_categoryV3Model.position3 ?? []),
          _buildPostionBottomView(_categoryV3Model.position3 ?? []),
        ],
      ),
    );
  }

  Widget _buildPostionTopView(List<CategoryInfoModel> listModel) {
    PositionWrap positionWrap = PositionWrap(listModel);
    if (listModel.length < 4 || positionWrap.largeList.isEmpty) {
      return Container();
    } else {
      return Row(
        // crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Wrap(
            spacing: _spacWidth,
            runSpacing: _spacWidth,
            children: positionWrap.largeList.map((e) {
              return _buildPositionLargeItem(e);
            }).toList(),
          ),
          SizedBox(
            width: _spacWidth,
          ),
          // StaggeredGridView.count(crossAxisCount: crossAxisCount)
          // GridView.extent(maxCrossAxisExtent: maxCrossAxisExtent)
          Expanded(
              child: Container(
                  // color: Colors.red,
                  // width: 1.sw - 30 - positionWrap.largeList.length * 118.w,
                  child: Wrap(
            spacing: _spacWidth,
            // alignment: WrapAlignmfnt.spaceBetween,
            runSpacing: _spacWidth,
            children: positionWrap.rightList.map((e) {
              return _buildPositionItem(e);
            }).toList(),
          )))
        ],
      );
    }
    // return Row();
  }

  Widget _buildPostionBottomView(List<CategoryInfoModel> listModel) {
    PositionWrap positionWrap = PositionWrap(listModel);
    if (positionWrap.bottomList.isEmpty) {
      return Container();
    }
    return Container(
      margin: EdgeInsets.only(
        top: 8.w,
      ),
      // color: Colors.red,
      child: Wrap(
        alignment: WrapAlignment.start,
        spacing: _spacWidth,
        runSpacing: _spacWidth,
        children: positionWrap.bottomList.map((e) {
          return _buildPositionItem(e);
        }).toList(),
      ),
    );
  }

  Widget _buildPositionLargeItem(CategoryInfoModel model) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: ClickUtils.debounce(() {
          _jingangJump(model);
        }),
        child: Container(
          width: 110.w,
          height: 144.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: Colors.green[50],
          ),
          child: Stack(
            children: [
              Positioned.fill(
                  child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: NetworkLoadImage.loadNetworkImage(
                        model.iconLarge,
                      ))),
              Positioned(
                top: 14.w,
                left: 10.w,
                right: 10.w,
                child: Text(
                  model.name ?? '',
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                      // fontWeight: FontWeight.w300,
                      fontFamily: 'PingFang SC'),
                ),
              )
            ],
          ),
        ));
  }

  Widget _buildPositionItem(CategoryInfoModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ClickUtils.debounce(() {
        _jingangJump(model);
      }),
      child: Container(
        width: 110.w,
        height: 68.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.green[50],
        ),
        child: Stack(
          children: [
            Positioned.fill(
                child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: NetworkLoadImage.loadNetworkImage(
                model.iconMini,
              ),
            )),
            Positioned(
              top: 8.w,
              left: 8.w,
              right: 8.w,
              child: Text(
                model.name ?? '',
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                    // fontWeight: FontWeight.w300,
                    fontFamily: 'PingFang SC'),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget announcementWidget() {
    var local =
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
    return _announcementRows.isNotEmpty
        ? Container(
            margin: EdgeInsets.only(top: 16, left: 16.w, right: 16.w),
            height: 48,
            padding: EdgeInsets.symmetric(horizontal: 12.w),
            // color: Colors.red,
            decoration: BoxDecoration(
                // color: Color(0xffF5F5F5),
                border: Border.all(
                  width: 1,
                  color: Colors.white,
                ),
                gradient: LinearGradient(colors: [
                  ThemeColor.hex('FFFFF8'),
                  ThemeColor.hex('E4FFDB'),
                  ThemeColor.hex('DBF8FF'),
                  // Colors.red
                ]),
                boxShadow: [
                  BoxShadow(
                    offset: Offset(3, -4),
                    blurRadius: 6,
                    spreadRadius: 0,
                    color: ThemeColor.hex('DEEDFF').withOpacity(0.36),
                  )
                ],
                borderRadius: BorderRadius.circular(8)),
            child: Row(children: [
              AutoImage(
                local.contains('zh')
                    ? Assets.homeAnnouncement
                    : Assets.homeAnnouncementEn,
                // width: 24.w,
                height: 28.w,
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 6.w),
                height: 18.w,
                width: 1,
                color: ThemeColor.colorTextB6,
              ),
              // Container(
              //   margin: EdgeInsets.only(left: 0, right: 6),
              //   child: Image.asset(
              //     'assets/images/home_announcement.png',
              //     width: 18,
              //     height: 18,
              //   ),
              // ),
              _announcementRows.isNotEmpty
                  ? Expanded(
                      child: Stack(
                      children: [
                        Positioned.fill(
                            child: CarouselSlider(
                          options: CarouselOptions(
                              autoPlay: true, scrollDirection: Axis.vertical),
                          items: _announcementRows.map((msg) {
                            return GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: ClickUtils.debounce(() {
                                // if (msg.type == 3) {
                                //   var web = WebVideoPage(msg.newsUrl ?? '');
                                //   // 占用是不显示原生的，所以为1的时候不显示
                                //   // web.needBar = true;
                                //   // web.needLongpressSave = false;
                                //   Navigator.of(context).push(MaterialPageRoute(
                                //       builder: (context) => web,
                                //       settings: RouteSettings(
                                //           name: "web_detail", arguments: "")));
                                // } else if (msg.type == 1) {
                                //   Navigator.of(context).push(MaterialPageRoute(
                                //       builder: (ctx) => WebProtocolDetailPage(
                                //           GlobalData.noticedetail(
                                //               context, msg.id ?? 0))));
                                // } else if (msg.type == 2) {
                                //   RouteManager.push(
                                //       context,
                                //       RoutMapping.gameDetail(
                                //           (msg.id ?? 0).toString(),
                                //           isVideo: false));
                                // }
                                UtilsOther.clickAnnouncementJump(msg, context);
                              }),
                              child: Container(
                                alignment: Alignment.centerLeft,
                                // height: 40,
                                margin: EdgeInsets.all(3),
                                padding: EdgeInsets.all(3),
                                child: Text(
                                  '${msg.title}',
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  textAlign: TextAlign.start,
                                  style: const TextStyle(
                                      color: ThemeColor.colorTextB2,
                                      fontSize: 12),
                                ),
                              ),
                            );
                          }).toList(),
                        )),
                        // Positioned(
                        //     top: 0,
                        //     left: 0,
                        //     right: 0,
                        //     child: Container(
                        //         height: 15,
                        //         decoration: BoxDecoration(
                        //             gradient: LinearGradient(
                        //                 colors: [
                        //               Color(0xffF5F5F5),
                        //               Color(0xffF5F5F5).withAlpha(0)
                        //             ],
                        //                 begin: Alignment.topCenter,
                        //                 end: Alignment.bottomCenter)))),
                        // Positioned(
                        //     bottom: 0,
                        //     left: 0,
                        //     right: 0,
                        //     child: Container(
                        //         height: 15,
                        //         decoration: BoxDecoration(
                        //             gradient: LinearGradient(
                        //                 colors: [
                        //               Color(0xffF5F5F5).withAlpha(0),
                        //               Color(0xffF5F5F5)
                        //             ],
                        //                 begin: Alignment.topCenter,
                        //                 end: Alignment.bottomCenter))))
                      ],
                    ))
                  : Container(),
              GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    DLog('msg');
                    RouteManager.push(
                      context,
                      RoutMapping.announcementsPage(),
                    );
                  },
                  child: SizedBox(
                    height: 40,
                    child: Row(
                      children: [
                        // Text(
                        //   S().more,
                        //   style: TextStyle(
                        //       color: Colors.black.withOpacity(0.4),
                        //       fontSize: 12),
                        // ),
                        Icon(
                          Icons.arrow_forward_ios_rounded,
                          size: 12,
                          color: Colors.black.withOpacity(0.4),
                        ),
                      ],
                    ),
                  ))
            ]))
        : Container();
  }

  @override
  Widget build(BuildContext context) {
    _spacWidth = (1.sw - 30 - 330.2.w) / 2.0;
    // var page = NewsFocusPage();
    // page.id = '2';
    // page.showType = 1;
    return Scaffold(
        backgroundColor: Colors.white,
        // image_home_new_bg

        body: Stack(
          children: [
            const Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: AutoImage(
                  Assets.imageHomeNewBg,
                  fit: BoxFit.fitWidth,
                )),
            Positioned.fill(
                child: Container(
                  width: 1.sw,
              // decoration: const BoxDecoration(
              //     image: DecorationImage(
              //         image: AssetImage(
              //           Assets.imageHomeNewBg,
              //         ),
              //         fit: BoxFit.fitWidth,
              //         alignment: Alignment.topCenter)),
              child: Column(
                children: [
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onDoubleTap: () {
                      _normalTableViewController.animateTo(0);
                    },

                    child: Consumer<ProviderIndexSetting>(
                        builder: (context, value, child) {
                      return HomeTitleBar(
                        showSearch: true,
                        weatherEntity: weatherEntity,
                        showQr: value.indexSetting.scan == 1,
                      );
                    }),

                    // ColorsTitleBar(x
                    //   weatherEntity,
                    //   isShowQr: true,
                    // )
                  ),
                  Expanded(
                      child: NormalTableView<FlowItemEntity>(
                    controller: _normalTableViewController,
                    header: (context) => Container(
                        child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Row(),
                        SizedBox(
                          height: 4.w,
                        ),
                        if (homeBannerList.isNotEmpty)
                          ScrollerCover(
                              homeBannerList.length,
                              (ctx, index) {
                                HomeCoverEntity each = homeBannerList[index];
                                _currentCover = each;
                                return
                                    //  Stack(
                                    // children: [

                                    GestureDetector(
                                  child: HomeCover(each),
                                  onTap: ClickUtils.debounce(() {
                                    // ThirdSDKAPI
                                    // yyy://page/web_detail?url=https://plat-h5.1kahui.cn/#/home?pageId=8285812173226250240&type=2"
                                    // if (each.linkUrl.contains('http') &&
                                    //     !each.linkUrl.startsWith('yyy://')) {
                                    //   var web = WebVideoPage(each.linkUrl);
                                    //   Navigator.of(context).push(MaterialPageRoute(
                                    //       builder: (context) => web,
                                    //       settings: RouteSettings(
                                    //           name: "web_in_view", arguments: "")));
                                    // } else {
                                    RouteManager.push(context, each.linkUrl);
                                    // }

                                    // appContext.channelApi.openAR();
                                  }),
                                  // )
                                  // ],
                                );
                              },
                              height: 129.w,
                              controller: _swipeController,
                              indicatorBuilder: (index, count) {
                                return CircleIndicator(index, count);
                              })
                        else
                          SafeArea(
                            bottom: false,
                            child: Container(
                              height: 129.w,
                              color: Colors.white,
                            ),
                          ),
                        // Visibility(child: countDownView())


                        _countDownTime > 0
                            ? countDownView()
                            : const SizedBox(height: 24),
                        jingangWidget(),

                        serviceWidget(),
                        baikeWidget(),
                        announcementWidget(),

                        // SizedBox(
                        //   height: 12,
                        // ),
                        Padding(
                            padding: EdgeInsets.only(
                              top: 24,
                              // bottom: 12,
                              left: 15,
                            ),
                            child: Row(
                              children: [
                                Text(
                                  S().home_app_news,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontFamily: "PingFang SC",
                                  ),
                                )
                              ],
                            )),
                      ],
                    )),
                    color: Colors.transparent,
                    itemBuilder: (context, item) {
                      return GestureDetector(
                        child: FlowItem(item),
                        onTap: ClickUtils.debounce(
                            () => RouteManager.push(context, item.linkUrl)),
                      );
                    },
                    pageSize: (pn) {
                      if (pn == 1) {
                        return 12;
                      }
                      return 15;
                    },
                    enableLoadMore: false,
                    getData: (pageNumber) async {
                      if (pageNumber == 1) {
                        await loadData();
                      }
                      List<ArticleListItem> lists = await API.shared.article
                          .articleInformationList(pageNumber, id: '2');
                      List<FlowItemEntity> allEntities = [];
                      lists.forEach((e) {
                        allEntities.add(FlowItemEntity.create(
                            e.title, e.publish_time, e.thumb, e.linkUrl,
                            labelText: e.tag,
                            author: e.author,
                            width: e.width,
                            height: e.height));
                      });
                      if (pageNumber == 1) {
                        topArticles.clear();
                      }
                      topArticles.addAll(allEntities);
                      for (var item in allEntities) {
                        item.useEnDate = true;
                      }
                      return allEntities;
                      // return [];
                    },
                  )),
                ],
              ),
            ))
          ],
        ));
  }
}

class PositionWrap {
  List<CategoryInfoModel> largeList = [];
  List<CategoryInfoModel> rightList = [];
  List<CategoryInfoModel> bottomList = [];

  PositionWrap(List<CategoryInfoModel> listModel) {
    if (listModel.length == 4 || listModel.length == 7) {
      largeList.addAll(listModel.sublist(0, 2));
      rightList.addAll(listModel.sublist(2, 4));
      bottomList.addAll(listModel.sublist(4, listModel.length));
    } else if (listModel.length == 5 || listModel.length == 8) {
      largeList.add(listModel.first);
      rightList.addAll(listModel.sublist(1, 5));
      bottomList.addAll(listModel.sublist(5, listModel.length));
    } else {
      bottomList.addAll(listModel);
    }
  }
}
